<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8" >
            <a-form-model-item label="单据号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billNo">
              <a-input v-model="model.billNo" placeholder="请输入单据号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="单据日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billDate">
              <j-date placeholder="请选择单据日期" v-model="model.billDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="调出库管员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warehouseEmpOut">
              <j-select-user-by-dep v-model="model.warehouseEmpOut" :multi="false"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="调出库房" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warehouseOut">
              <j-search-select-tag v-model="model.warehouseOut" dict="mdm_warehouse,warehouse_name,id"  />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="调入库房" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warehouseIn">
              <j-search-select-tag v-model="model.warehouseIn" dict="mdm_warehouse,warehouse_name,id"  />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="调入库管员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warehouseEmpIn">
              <j-select-user-by-dep v-model="model.warehouseEmpIn" :multi="false"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="16">
            <a-form-model-item label="备注" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="remark">
              <a-textarea v-model="model.remark" rows="2" placeholder="请输入备注" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="库存调拨明细" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="mmStockTransferDetailTable.loading"
          :columns="mmStockTransferDetailTable.columns"
          :dataSource="mmStockTransferDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"
          :actionAddButton="false"
          @added="detailAdded"
          @valueChange="qtyAndPriceChange">
          <div slot="buttonBefore">
            <div class="action-button">
              <a-button type="primary" icon="plus" @click="chooseMaterialStock" :disabled="formDisabled">新增</a-button>
              <span class="gap"></span>
            </div>
          </div>
        </j-editable-table>
        <j-popup-onl-report ref="jPopupOnlReport" code="mm_material_stock_pop" multi="true" :param="materialStockParam" @ok="stockPopupCallback"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

  import { getAction } from '@/api/manage'
  import { FormTypes,getRefPromise,VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
  import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
  import { validateDuplicateValue } from '@/utils/util'
  import moment from "moment";
  import {initDictOptions} from "@/components/dict/JDictSelectUtil";

  export default {
    name: 'MmStockTransferForm',
    mixins: [JEditableTableModelMixin],
    components: {
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        model:{
          billDate: moment(new Date()).format('YYYY-MM-DD'),
          status: "01"
        },
        materialStockParam: {},
        stockCheck: false,
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
           billDate: [
              { required: true, message: '请输入单据日期!'},
           ],
           warehouseOut: [
              { required: true, message: '请输入调出库房!'},
           ],
           warehouseIn: [
              { required: true, message: '请输入调入库房!'},
           ],
        },
        refKeys: ['mmStockTransferDetail', ],
        tableKeys:['mmStockTransferDetail', ],
        activeKey: 'mmStockTransferDetail',
        // 库存调拨明细
        mmStockTransferDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '物料描述',
              key: 'materialDesc',
              type: FormTypes.popup,
              popupCode: "mm_material_stock_pop",
              orgFields: 'material_id,material_no,material_desc,unit,stock_qty_available,batch_no,unit_price,available_sum_price,storage_location_id,max_stock_qty_available',
              destFields: 'materialId,materialNo,materialDesc,unit,billQty,batchOut,unitPrice,sumPrice,storageLocationOut,maxStockQtyAvailable',
              width:"260px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '单位',
              key: 'unit',
              type: FormTypes.sel_search,
              dictCode:"mdm_unit,unit_name,unit_code",
              width:"110px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true,
            },
            {
              title: '制单数量',
              key: 'billQty',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [
                {required: true, message: '${title}不能为空'},
                {
                  handler(type, value, row, column, callback, target) {
                    let {values} = target.getValuesSync({validate: false, rowIds: [row.id]});
                    if (type === 'blur' || type === 'getValues') {
                      if (value <= 0) {
                        callback(false, '请输入大于零的数')
                        return;
                      }else if (value > values[0].maxStockQtyAvailable){
                          callback(false, '${title}不能超出可用库存量：' + values[0].maxStockQtyAvailable)
                          return;
                      }else{
                          callback(true)
                      }
                    } else {
                       callback();
                    }
                  },
                },
              ],
            },
            {
              title: '单价',
              key: 'unitPrice',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '金额',
              key: 'sumPrice',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '调入库位',
              key: 'storageLocationIn',
              type: FormTypes.sel_search,
              width:"160px",
              placeholder: '请输入${title}',
              defaultValue:'',
              options:[]
            },
            {
              title: '调入批次',
              key: 'batchIn',
              type: FormTypes.input,
              width:"160px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '备注',
              key: 'remark',
              type: FormTypes.input,
              width:"240px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '调出库位',
              key: 'storageLocationOut',
              type: FormTypes.sel_search,
              dictCode:"mdm_storage_location,location_no,id",
              width:"160px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true,
            },
            {
              title: '调出批次',
              key: 'batchOut',
              type: FormTypes.input,
              width:"160px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true,
            },
            {
              title: '行号',
              key: 'lineNo',
              type: FormTypes.inputNumber,
              width:"70px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true,
            },
            {
              title: 'materialId',
              key: 'materialId',
              type: "hidden"
            },
            {
              title: 'materialNo',
              key: 'materialNo',
              type: "hidden"
            },
            {
              title: '调拨数量',
              key: 'transferQty',
              type: "hidden",
            },
            {
              title: '最大可用库存量',
              key: 'maxStockQtyAvailable',
              type: 'hidden',
            },
          ]
        },
        url: {
          add: "/mm/stockTransfer/add",
          edit: "/mm/stockTransfer/edit",
          queryById: "/mm/stockTransfer/queryById",
          genCode: "/mdm/codeRule/genCode",
          checkWarehouseAndLocation: "/mm/stockTransfer/checkWarehouseAndLocation",
          materialStockList: "mm/materialStock/list",
          mmStockTransferDetail: {
            list: '/mm/stockTransfer/queryMmStockTransferDetailByMainId'
          },
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled || this.model.status !== '01'
      },
    },
    watch: {
      'model.warehouseOut': {
        deep: true,
        handler(newVal, oldVal) {
          if(this.stockCheck){
            this.stockCheck = !this.stockCheck;
            return;
          }
          let mmStockTransferDetail = this.$refs[this.refKeys[0]];
          let {values} = mmStockTransferDetail.getValuesAsync({validate: false})
          if(values && values.length > 0){
            this.$message.error("已有调拨明细，不能修改调出库房!")
            this.stockCheck = true;
            this.model.warehouseOut = oldVal
          }
        }
      },
      'model.warehouseIn': {
        deep: true,
        handler(newVal, oldVal) {
          if(this.stockCheck){
            this.stockCheck = !this.stockCheck;
            return;
          }
          let mmStockTransferDetail = this.$refs[this.refKeys[0]];
          let {values} = mmStockTransferDetail.getValuesAsync({validate: false})
          if(values && values.length > 0){
            let hasVal = values.some(row => row.storageLocationIn)
            if(hasVal){
              this.$message.error("调拨明细已经填写库位，不能修改调入库房!")
              this.stockCheck = true;
              this.model.warehouseIn = oldVal
            }
          }
          let storageLocationIn = this.mmStockTransferDetailTable.columns[5];
          if(newVal){
            let dictCode = "mdm_storage_location,location_no,id" + encodeURIComponent(",enable_flag='1' and warehouse_id='"+ newVal +"'")
            initDictOptions(dictCode).then(res => {
              if (res.success && res.result.length>0) {
                storageLocationIn.options = res.result
              } else {
                storageLocationIn.options = []
                this.$message.error("未找到库位信息!")
              }
            })
          }else{
            storageLocationIn.options=[]
          }
        }
      },
    },
    created () {
    },
    methods: {
      addBefore(){
        this.genBillNo();
        this.mmStockTransferDetailTable.dataSource=[]
      },
      genBillNo(){
        this.confirmLoading = true
        getAction(this.url.genCode, {codeType: '18'}).then(res => {
          if (res.success) {
            this.model.billNo = res.result;
          }
        }).finally(() => {
          this.confirmLoading = false
        })
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      editBefore(record){
        record.id = record.pid;
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.pid) {
          let params = { id: this.model.pid }
          this.requestSubTableData(this.url.mmStockTransferDetail.list, params, this.mmStockTransferDetailTable)
        }
      },
      //校验所有一对一子表表单
      validateSubForm(allValues){
          return new Promise((resolve,reject)=>{
            Promise.all([
            ]).then(() => {
              resolve(allValues)
            }).catch(e => {
              if (e.error === VALIDATE_NO_PASSED) {
                // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
              } else {
                console.error(e)
              }
            })
          })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          mmStockTransferDetailList: allValues.tablesValue[0].values,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      qtyAndPriceChange(parm) {
        if (parm && parm['column'] && parm['row'] && parm['target']) {
          let cols = ['billQty', 'sumPrice', 'unitPrice'];
          let key = parm.column.key;
          if (cols.includes(key)) {
            let editableTable = parm['target'];
            // 重新计算当前行总金额
            if (key === cols[0] || key === cols[2]) {
              let unitPrice = parm.row[cols[2]] || 0;
              let qty = parm.row[cols[0]] || 0;
              let sumPrice = Math.round(unitPrice * qty * 100) / 100;
              editableTable.setValues([{rowKey: parm.row.id, values: {[cols[1]]: sumPrice}}]);
            }
            // 重新计算单价
            if (key === cols[1]) {
              let sumPrice = parm.row[cols[1]] || 0;
              let qty = parm.row[cols[0]] || 0;
              if (qty != 0) {
                let unitPrice = Math.round(sumPrice / qty * 100) / 100;
                editableTable.setValues([{rowKey: parm.row.id, values: {[cols[2]]: unitPrice}}]);
              }
            }
            // 重新计算统计列
            editableTable.recalcOneStatisticsColumn(cols[0]);
            editableTable.recalcOneStatisticsColumn(cols[1]);
          }
        }
      },
      detailAdded: function (obj) {
        let editTable = this.$refs[this.refKeys[0]];
        let lineNo = this.generateLineNo();
        editTable.setValues([{rowKey: obj.row.id, values: {lineNo: lineNo}}])
      },
      /** 生成行号 */
      generateLineNo() {
        let editTable = this.$refs[this.refKeys[0]];
        let rows = editTable.rows;
        let num = 10;
        if (rows.length > 1) {
          let lastId = editTable.getCleanId(rows[rows.length - 2].id)
          let {values} = editTable.getValuesSync({validate: false, rowIds: [lastId]});
          num = Number(values[0].lineNo) + 10
        }
        return num
      },
      chooseMaterialStock() {
        if (!this.model.warehouseOut) {
          this.$message.error("请先选择调出库房！")
          return
        }
        this.materialStockParam = {warehouseId: this.model.warehouseOut}
        this.$refs.jPopupOnlReport.show();
      },
      stockPopupCallback(rows) {
        if (rows && rows.length > 0) {
          let mmStockTransferDetail = this.$refs[this.refKeys[0]];
          let oldData = mmStockTransferDetail.getValuesSync();
          let column = this.mmStockTransferDetailTable.columns.find(col => col.key === 'materialDesc')
          let orgFieldsArr = ['material_id','material_no','material_desc','unit','stock_qty_available','batch_no','unit_price','available_sum_price','storage_location_id','max_stock_qty_available'];
          let destFieldsArr = ['materialId','materialNo','materialDesc','unit','billQty','batchOut','unitPrice','sumPrice','storageLocationOut','maxStockQtyAvailable'];
          let addRow, addData
          for (let i = 0; i < rows.length; i++) {
            if (!(i === 0 && oldData && oldData.values && oldData.values.length === 1 && !oldData.values[0].materialDesc)) {
              mmStockTransferDetail.add();
            }
            addRow = mmStockTransferDetail.rows[mmStockTransferDetail.rows.length - 1];
            // key转换
            for (let j = 0; j < orgFieldsArr.length; j++) {
              rows[i][destFieldsArr[j]] = rows[i][orgFieldsArr[j]];
              if (destFieldsArr[j] !== orgFieldsArr[j]) {
                delete rows[i][orgFieldsArr[j]]
              }
            }
            rows[i].batchIn = rows[i].batchOut
            addData = Object.assign({}, rows[i])
            mmStockTransferDetail.popupCallback(addData.materialDesc, addData, 'materialDesc' + addRow.id, addRow, column)
          }
        }
      },
    }
  }
</script>

<style scoped>
.action-button {
  margin-bottom: 8px;
}
.gap {
  padding-left: 8px;
}
</style>